<?php 
/*
*  LEGAL NOTICE
* Prestaworks® - http://www.prestaworks.com
Copyright (c) 2008
by Prestaworks
* Permission is hereby granted, to the buyer of this software to use it freely in association with prestashop. 
* The buyer are free to use/edit/modify this software in anyway he/she see fit.
* The buyer are NOT allowed to redistribute this module in anyway or resell it or redistribute it to third party.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class prestaworksAddStuff extends Module
{
    public function __construct()
    {
        $this->name = 'prestaworksAddStuff';
        $this->tab = 'Prestaworks.com';
        $this->version = '0.1';
        
        parent::__construct();
 
        /* The parent construct is required for translations */
        $this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Prestaworks Addstuff');
        $this->description = $this->l('Add various scripts to your e-cart, language support.');
    }

	function install()
	{
	if (!parent::install() OR !$this->registerHook('rightColumn'))
		return false;
		$query = 'CREATE TABLE '._DB_PREFIX_.'prestaworks_addstuff (`id_lang` int(10) unsigned NOT NULL, `stuff` text NOT NULL, `header` tinytext NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;';
		if (!Db::getInstance()->Execute($query))
	 		return false;
       return true;
   }
	
	function uninstall()
	{
		if (!parent::uninstall())
		return false;
		$query = 'DROP TABLE '._DB_PREFIX_.'prestaworks_addstuff';
		if (!Db::getInstance()->Execute($query))
	 		return false;	    
			
		return true;
	}
	
	function addStuff()
	{
	 	/* Multilingual text */
	 	$languages = Language::getLanguages();
	 	$defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
	 	if (!$languages)
	 		return false;
			
		//Empty old stuff
		if(!Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'prestaworks_addstuff WHERE 1=1'))
			return false;
			
	 	foreach ($languages AS $language)
		{
		if ((!empty($_POST['stuff_'.$language['id_lang']])))
	 	 	{
			//Insert new content
	 	 		if (!Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'prestaworks_addstuff (`id_lang`,`stuff`,`header`) VALUES ('.$language['id_lang'].', \''.$_POST['stuff_'.$language['id_lang']].'\',\''.pSQL($_POST['header_'.$language['id_lang']]).'\')'))
	 	 			return false;
			}
		else
		{
		//add default to not set languages
	 	 		if (!Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'prestaworks_addstuff (`id_lang`,`stuff`,`header`) VALUES ('.$language['id_lang'].', \''.$_POST['stuff_'.$defaultLanguage].'\',\''.pSQL($_POST['header_'.$defaultLanguage]).'\')'))
	 	 			return false;
		}
		}
	 	return true;
	}
	
	function getContent()
    {
		$this->_html = '<h2>'.$this->displayName.'</h2>
		<script type="text/javascript" src="'.$this->_path.'prestaworksCustomNews.js"></script>';
	
		if (isset($_POST['addstuff']))
     	{
     	 	if (!$this->addStuff())
     	 	 	$this->_html .= $this->displayError($this->l('An error occurred'));
     	 	else
     	 	 	$this->_html .= $this->displayConfirmation($this->l('Success'));
     	}	
     	

     	$this->_displayForm();
    
        return $this->_html;
    }
	
	public function _displayForm()
	{
		global $cookie;
	 	/* Language */
	 	$defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages();
		$divLangName = 'stuff¤header';

		$oldrows = $this->getStuff();
	 	$this->_html .= '
		<script type="text/javascript">
			id_language = Number('.$defaultLanguage.');
		</script>
	 	<fieldset>
			<legend><img src="'.$this->_path.'add.png" alt="" title="" /> '.$this->l('Add content to block').'</legend>
			<form method="post" action="'.$_SERVER['REQUEST_URI'].'" enctype="multipart/form-data">';
				
			$this->_html .= '<label>'.$this->l('header:').'</label><div class="margin-form">';
			foreach ($languages as $language)
			{
			$header = '';
			if($oldrows)
			{
				foreach($oldrows AS $old)
				{
					if($old['id_lang']==$language['id_lang'])
					{
						$header = $old['header'];
					}
				}
			}
					$this->_html .= '
					<div id="header_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<input type="text" name="header_'.$language['id_lang'].'" id="header_'.$language['id_lang'].'" value="'.$header.'" /><sup> *</sup>
					</div>';
			}
			$this->_html .= $this->displayFlags($languages, $defaultLanguage, $divLangName, 'header', true);
			
			$this->_html .= '<div class="clear"></div>
				</div><label>'.$this->l('content:').'</label><div class="margin-form">';
			foreach ($languages as $language)
			{
			
			$stuff = '';
			if($oldrows)
			{
				foreach($oldrows AS $old)
				{
					if($old['id_lang']==$language['id_lang'])
					{
						$stuff = $old['stuff'];
					}
				}
			}
			
				$this->_html .= '
					<div id="stuff_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<textarea cols="30" rows="10" name="stuff_'.$language['id_lang'].'" id="stuff_'.$language['id_lang'].'">'.$stuff.'</textarea><sup> *</sup>
					</div>';
			}
			$this->_html .= $this->displayFlags($languages, $defaultLanguage, $divLangName, 'stuff', true);
			
			$this->_html .= '<div class="clear"></div>';
				
				$this->_html .= '<div class="margin-form">
					<input type="submit" class="button" name="addstuff" value="'.$this->l('Save').'" />
				</div>
			</form>
		</fieldset>';
		
		$this->_html .='<fieldset class="space">
			<legend><img src="../img/admin/unknown.gif" alt="" class="middle" />Info</legend>
			 <h4>This module lets you add custom stuff to your webshop in either the right or left column.</h4>
			 '.$this->l('User instructions:').'
			 <ol>
			 	<li>Copy the script or image url to the boxes.</li>
			 	<li>If you wan\'t different content for different languages, just select a different language by clicking on the flag.</li>
			 	<li>If language is empty, default language content will be inserted.</li>
			</ol>
			<h4>'.$this->l('Do you want more?').'</h4>
			Check out <a href="http://www.prestaworks.com" title="www.prestaworks.com" alt="www.prestaworks.com">www.prestaworks.com</a> for more modules and themes for prestashop!
		</fieldset>';
	}
	
	
	function getStuff()
	{
	 	$result = array();
	 	/* Get newsl */
		$query = 'SELECT `stuff`, `header`, `id_lang` FROM '._DB_PREFIX_.'prestaworks_addstuff';
	 	if (!$stuffs = Db::getInstance()->ExecuteS($query))
	 		return false;
	 	$i = 0;
		
	 	foreach ($stuffs AS $stuff)
	 	{
		 	$result[$i]['stuff'] = $stuff['stuff'];
			$result[$i]['header'] = $stuff['header'];
			$result[$i]['id_lang'] = $stuff['id_lang'];
			$i++;
		}
	 	return $result;
	}
	
	function loadStuff($lang)
	{
	 	$result = array();
	 	/* Get newsl */
		$query = 'SELECT `stuff`, `header` FROM '._DB_PREFIX_.'prestaworks_addstuff WHERE `id_lang`='.$lang;
	 	if (!$stuffs = Db::getInstance()->ExecuteS($query))
	 		return false;
	 	$i = 0;
		
	 	foreach ($stuffs AS $stuff)
	 	{
		 	$result[$i]['stuff'] = $stuff['stuff'];
			$result[$i]['header'] = $stuff['header'];
			$i++;
		}
	 	return $result;
	}
	
	function hookLeftColumn($params)
	{
	 	return $this->hookLeftColumn($params);
	}
	
	function hookRightColumn($params)
	{
		global $cookie, $smarty;
	 	$stuff = $this->loadStuff(intval($cookie->id_lang));
		
		$smarty->assign(array(
		'stuff' => $stuff[0]['stuff'],
		'header' => $stuff[0]['header']
));

		return $this->display(__FILE__, 'prestaworksAddStuff.tpl');
	}

} 
?> 